<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <el-col :lg="4" :md="4" :sm="6" :xl="4" :xs="9">
        <div class="head-container">
          <el-input
              v-model="deptName"
              class="filter-item"
              clearable
              placeholder="输入公司名称搜索"
              prefix-icon="el-icon-search"
              size="small"
              @input="getDeptDatas"
          />
        </div>
        <el-tree
            :data="deptDatas"
            :expand-on-click-node="false"
            :props="defaultProps"
            default-expand-all
            @node-click="handleNodeClick"
        />
      </el-col>
      <!--公司-->
      <el-col :lg="20" :md="20" :sm="18" :xl="20" :xs="15">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
                v-model="query.keyword"
                class="filter-item"
                clearable
                placeholder="输入名称或者邮箱搜索"
                size="small"
                style="width: 200px;"
                @keyup.enter.native="crud.toQuery"
            />
            <el-select
                v-model="query.status"
                class="filter-item"
                clearable
                placeholder="状态"
                size="small"
                style="width: 90px"
                @change="crud.toQuery"
            >
              <el-option
                  v-for="item in enabledTypeOptions"
                  :key="item.key"
                  :label="item.display_name"
                  :value="item.key"
              />
            </el-select>
            <rrOperation :crud="crud"/>
          </div>
          <crudOperation :permission="permission" show=""/>
        </div>
        <!--表单渲染-->
        <el-dialog :before-close="crud.cancelCU" :close-on-click-modal="false" :title="crud.status.title"
                   :visible.sync="crud.status.cu > 0" append-to-body width="570px">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="66px" size="small">
<!--            <el-form-item label="编码" prop="code">-->
<!--              <el-input v-model="form.code"/>-->
<!--            </el-form-item>-->
            <el-form-item label="公司名" prop="name">
              <el-input v-model="form.name"/>
            </el-form-item>
            <el-form-item label="领导" prop="leader">
              <el-input v-model="form.leader"/>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" maxlength="11" oninput="value=value.replace(/[^\d]/g,'')" show-word-limit/>
            </el-form-item>
<!--            <el-form-item label="昵称" prop="nickName">-->
<!--              <el-input v-model="form.nickName" maxlength="20" show-word-limit/>-->
<!--            </el-form-item>-->
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email"/>
            </el-form-item>
            <!--            <el-form-item label="部门" prop="deptId">-->
            <!--              <treeselect-->
            <!--                v-model="form.dept.id"-->
            <!--                :options="depts"-->
            <!--                style="width: 178px"-->
            <!--                placeholder="选择部门"-->
            <!--                @select="selectFun"-->
            <!--              />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="岗位" prop="job">-->
            <!--              <el-select v-model="form.job.id" style="width: 178px" placeholder="请先选择岗位">-->
            <!--                <el-option-->
            <!--                  v-for="(item, index) in jobs"-->
            <!--                  :key="item.name + index"-->
            <!--                  :label="item.name"-->
            <!--                  :value="item.id"-->
            <!--                />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="性别">
              <el-radio-group v-model="form.sex" style="width: 178px">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                :disabled="form.id === user.id"
                v-model="form.status"
                class="filter-item"
                clearable
                style="width: 185px"
                placeholder="状态"
                size="small"
                @change="crud.toQuery"
              >
                <el-option
                  v-for="item in dict.common_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
<!--              <el-radio-group v-model="form.status" :disabled="form.id === user.id">-->
<!--                <el-radio-->
<!--                    v-for="item in dict.common_status"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                >{{ item.label }}-->
<!--                </el-radio>-->
<!--              </el-radio-group>-->
            </el-form-item>
            <el-form-item label="备注" prop="remark" >
              <el-input v-model="form.remark"   style="width: 180px"/>
            </el-form-item>
<!--            <el-form-item label="角色" prop="roles" >-->
<!--              <el-select-->
<!--                  v-model="form.roles"-->
<!--                  multiple-->
<!--                  placeholder="请选择角色"-->
<!--                  style="width: 446px"-->
<!--                  @change="changeRole"-->
<!--                  @remove-tag="deleteTag"-->
<!--              >-->
<!--                <el-option-->
<!--                    v-for="item in roles"-->
<!--                    :label="item.name"-->
<!--                    :value="item.id"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item v-if="form.pid !== 0" label="上级公司" prop="pid" style="margin-bottom: 0;">
              <treeselect v-model="form.pid" :normalizer="normalizer" :options="deptDatas" placeholder="选择上级公司"
                          style="width: 446px;"/>
            </el-form-item>
            <!--key="item.name"  disabled="level !== 1 && item.level <= level"-->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.cu === 2" type="primary" @click="submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" border v-loading="crud.loading" :data="crud.data" style="width: 100%;"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}" default-expand-all row-key="id" @select="crud.selectChange"
                  :normalizer="normalizer"
                  @selection-change="crud.selectionChangeHandler"
                  @row-dblclick="crud.toEdit($event)">
          <el-table-column :render-header="crud.renderHeader" :selectable="checkboxT" type="selection" width="60"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('name')" :show-overflow-tooltip="true" label="公司名"
                           prop="name"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('phone')" :show-overflow-tooltip="true" label="电话" prop="phone"
                           width="100"/>
          、
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('leader')" :show-overflow-tooltip="true" label="领导" prop="leader"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('code')" :show-overflow-tooltip="true" label="编码" prop="code"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('phone')" :show-overflow-tooltip="true" label="上级电话" prop="phone"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('pname')" :show-overflow-tooltip="true" label="上级名称" prop="pname"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('pcode')" :show-overflow-tooltip="true" label="上级编码" prop="pcode"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" label="备注" prop="remark"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('enabled')" align="center" label="状态" prop="status">
            <template slot-scope="scope">
              <el-switch
                  v-model="scope.row.status == 1"
                  :disabled="user.id === scope.row.id"
                  active-color="#409EFF"
                  inactive-color="#F56C6C"
                  @change="changeEnabled(scope.row, scope.row.status)"
              />
            </template>
          </el-table-column>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createTime')" :show-overflow-tooltip="true" label="创建日期"
                           prop="createTime" width="140">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
              v-permission="['admin','user:edit','user:del']"
              align="center"
              fixed="right"
              label="操作"
              width="125"
          >
            <template slot-scope="scope">
              <udOperation
                  :data="scope.row"
                  :disabled-dle="scope.row.id === user.id||scope.row.enabled"
                  :permission="permission"
              />
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudCompany from '@/api/system/company'
import {isvalidPhone} from '@/utils/validate'
import {getCompany} from '@/api/system/company'
import {getAll, getLevel} from '@/api/system/role'
import {getAllJob} from '@/api/system/job'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import {mapGetters} from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

let userRoles = []
// crud交由presenter持有
const defaultCrud = CRUD({title: '公司', url: 'api/sysCompany', crudMethod: {...crudCompany}})
const defaultForm = {
  username: null,
  nickName: null,
  sex: '男',
  leader: '',
  email: null,
  enabled: 'false',
  roles: [],
  job: {id: null},
  dept: {id: null},
  phone: null
}
export default {
  name: 'company',
  components: {Treeselect, crudOperation, rrOperation, udOperation, pagination},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['common_status',],
  data() {
    // 自定义验证
    // const validPhone = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error('请输入电话号码'))
    //   } else if (!isvalidPhone(value)) {
    //     callback(new Error('请输入正确的11位手机号码'))
    //   } else {
    //     callback()
    //   }
    // }
    const validPhone = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }


    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], jobs: [], level: 3, roles: [],
      defaultProps: {children: 'children', label: 'name'},
      companyList: [],
      permission: {
        add: ['admin', 'sysCompany:add'],
        edit: ['admin', 'sysCompany:edit'],
        del: ['admin', 'sysCompany:del'],
        import: ['admin', 'sysCompany:import'],
        export: ['admin', 'sysCompany:export'],
      },
      enabledTypeOptions: [
        {key: 1, display_name: '启用'},
        {key: 0, display_name: '禁用'}
      ],
      rules: {
        // code: [
        //   {required: true, message: '请输入编码', trigger: 'blur'},
        // ],
        name: [
          {required: true, message: '请输入公司名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: '请输入公司昵称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        email: [
          // {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        roles: [
          {required: true, message: '请选择角色', trigger: 'blur'},
        ],
        // phone: [
        //   { message: '请输入正确的手机号码', trigger: 'blur',validator: validPhone}
        // ],
        deptId: [
          {required: true, trigger: 'blur', validator: this.valiDeptId}
        ],
        job: [
          {required: true, trigger: 'blur', validator: this.valiJob}
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.$nextTick(() => {
      this.getDeptDatas()
      this.crud.toQuery()
      this.crud.msg.add = '新增成功，默认密码：123456'
    })
    // console.log(name)
  },
  mounted: function () {
    const that = this
    this.getDeptDatas()
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    submitCU(){
      this.crud.submitCU()
      setTimeout(()=>{
        this.getDeptDatas()
      },500)
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function (data, index) {
        const role = {id: data}
        userRoles.push(role)
      })
    },
    valiDeptId(rule, value, callback) {
      if (!this.form.dept.id) {
        callback(new Error('请选择部门'))
      } else {
        callback()
      }
    },
    valiJob(rule, value, callback) {
      if (!this.form.job.id) {
        callback(new Error('请选择岗位'))
      } else {
        callback()
      }
    },
    [CRUD.HOOK.afterDelete](crud, data) {
      this.getDeptDatas()
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = []
      userRoles.forEach(function (role, index) {
        initRoles.push(role.id)
      })
      crud.form.roles = initRoles
      this.getDeptDatas()
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    beforeInit() {
      this.url = 'api/sysCompany'
      return true
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getCompanys()
      this.getRoles()
      this.getRoleLevel()
      this.getJobs(null)
      form.enabled = form.enabled.toString()
    },

    [CRUD.HOOK.afterSubmit](crud, form) {
      this.getDeptDatas()
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.getJobs()
      userRoles = []
      const roles = []
      form.roles.forEach(function (role, index) {
        roles.push(role.id)
        // 初始化编辑时候的角色
        const rol = {id: role.id}
        userRoles.push(rol)
      })
      form.roles = roles
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      // if (!crud.form.dept.id) {
      //   this.$message({
      //     message: '部门不能为空',
      //     type: 'warning'
      //   })
      //   return false
      // } else if (!crud.form.job.id) {
      //   this.$message({
      //     message: '岗位不能为空',
      //     type: 'warning'
      //   })
      //   return false
      // } else
        if (this.roles.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }
      crud.form.roles = userRoles
      return true
    },
    // 获取左侧部门数据
    getDeptDatas() {
      const sort = 'id,desc'
      const params = {sort: sort}
      if (this.deptName) {
        params['name'] = this.deptName
      }
      getCompany(params).then(res => {
        this.deptDatas = res.data.content
      })
    },
    // 获取弹窗内部门数据
    getCompanys() {
      getCompany({enabled: true}).then(res => {
        this.depts = res.content
      })
    },
    // 切换部门
    handleNodeClick(data) {
      const dataStatus = []
      console.log('data',data)
      function resetStatus(datas) {
        console.log('datas',datas)
        if(datas){
          dataStatus.push(datas.id)
          if (datas.children) {
            datas.children.map((e) => {
              dataStatus.push(e.id)
              if (e.children) {
                resetStatus(e)
              }
            })
          }
        }
      }
      resetStatus(data)
      console.log('dataStatus',dataStatus)
      let list = Array.from(new Set(dataStatus))
      console.log('list',list)
      this.query.ids = list.join(',')
      // if (data.pid === 0) {
      //   this.query.ids = null
      // } else {
      // this.query.ids = data.id
      // }
      this.crud.toQuery()
    },
    // 改变状态
    changeEnabled(data, val) {
      console.log('data',data,val)
      let info = data.status == true?'禁用':'启用'
      this.$confirm('此操作将 "' + info + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        data.status = data.status == true?0:1
        crudCompany.edit(data).then(res => {
          this.crud.notify(info + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          // data.status = !data.status
        })
      }).catch(() => {
        // data.status = !data.status
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res.data.content
      }).catch(() => {
      })
    },
    // 获取弹窗内岗位数据
    getJobs(id) {
      getAllJob(id).then(res => {
        this.jobs = res.content
      }).catch(() => {
      })
    },
    // 点击部门搜索对应的岗位
    selectFun(node, instanceId) {
      this.getJobs(node.id)
      this.form.job.id = null
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => {
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id && !row.enabled
    }
  }
}
</script>

<style scoped>
</style>
